//
//  UIImageView+ARRessume.m
//  ARWebImage
//
//  Created by 包日守 on 15/11/6.
//  Copyright © 2015年 Arise. All rights reserved.
//

#import "UIImageView+ARRessume.h"
#import <objc/runtime.h>

static const char *arRessume;
static const char *arProgress;

@implementation UIImageView (ARRessume)

- (void) ar_clear
{
    self.image = nil;
    [self.ar_ressume pauseDownLoad];
    self.ar_ressume = nil;
    
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }


}

- (ZFProgressView *) ar_progress
{
    
    
    ZFProgressView *progress = objc_getAssociatedObject(self, &arProgress);
    if (progress == nil) {
        progress = [[ZFProgressView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        progress.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2);
        [self addSubview:progress];
        
        
        
        progress.Percentage = 0;
        
        progress.progressLabel.hidden = YES;
        progress.progressLineWidth = 3;
        progress.backgourndLineWidth = 2;
        progress.progressStrokeColor = [UIColor colorWithRed:74.0/255 green:169.0/255 blue:254.0/255 alpha:1];
        progress.backgroundStrokeColor = [UIColor groupTableViewBackgroundColor];
        
    }
    return progress;
}


- (void) setAr_progress:(ZFProgressView *)ar_progress
{
    objc_setAssociatedObject(self, &arProgress, ar_progress, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

- (ARRessume *) ar_ressume
{
    ARRessume *ressume =  objc_getAssociatedObject(self, &arRessume);
    return ressume;


}

- (void) setAr_ressume:(ARRessume *)ar_ressume
{

    objc_setAssociatedObject(self, &arRessume, ar_ressume, OBJC_ASSOCIATION_RETAIN);
}

- (void) ar_setImageWithURL:(NSString *)url
{
    
    [self ar_clear];
    
    self.ar_ressume = [[ARRessume alloc] init];
    self.ar_ressume.stringURL = url;
    
    __weak typeof(self) vc = self;
    
    [self.ar_ressume setSuccess:^(NSData *data) {
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            for (UIView * view in vc.subviews) {
                [view removeFromSuperview];
            }
            
            vc.image = [UIImage imageWithData:data];
            
        });
    }];
    
    [self.ar_ressume setLoadingData:^(NSNumber *loadSize, NSNumber *fileSize) {
       
        dispatch_async(dispatch_get_main_queue(), ^{
            vc.ar_progress.Percentage = (float)[loadSize longLongValue]/[fileSize longLongValue];
        });
        
    }];
    

    
    [self.ar_ressume startDownload];
}

@end
